const app = getApp()
const { uploadLocation, getNearbyLocations } = require('../../utils/api')

Page({
    data: {
        longitude: 0,
        latitude: 0,
        markers: [],
        accuracy: 0,
        lastUpdate: '--',
        locationInterval: null,
        mapContext: null,
        isFirstLocation: true,
        showCallout: false,
        //用户信息显示
    calloutLeft: 0,
    calloutTop: 0,
    currentUser: null
      },

  onLoad() {
    this.initMap()
    //this.startLocationSharing()
  },

  // 初始化地图
  initMap() {
    this.setData({
      mapContext: wx.createMapContext('map')
    })
  },

  // 开始位置共享
  startLocationSharing() {
    this.getLocationAndUpload()
    this.setData({
      locationInterval: setInterval(() => this.getLocationAndUpload(), 5000)
    })
  },

  // 获取位置并上传
  getLocationAndUpload() {
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: (res) => {
        this.updateMyLocation(res)
        this.uploadLocation(res)
        this.fetchNearbyUsers(res)
      },
      fail: (err) => {
        console.error('定位失败:', err)
        wx.showToast({ title: '获取位置失败', icon: 'none' })
      }
    })
  },

  // 更新我的位置标记
  updateMyLocation(res) {
    const { latitude, longitude, accuracy } = res
    const myMarker = {
      id: 'myLocation',
      latitude,
      longitude,
      iconPath: '/images/my-location.png',
      width: 32,
      height: 32,
      anchor: { x: 0.5, y: 0.5 },
      callout: {
        content: '我的位置',
        color: '#fff',
        fontSize: 12,
        bgColor: '#07c160',
        padding: 5,
        borderRadius: 4,
        display: 'ALWAYS'
      }
    }

    this.setData({
      latitude,
      longitude,
      accuracy: accuracy.toFixed(0),
      lastUpdate: new Date().toLocaleTimeString(),
      markers: [...this.data.markers.filter(m => m.id !== 'myLocation'), myMarker]
    })

    if (this.data.isFirstLocation) {
      this.centerLocation()
      this.setData({ isFirstLocation: false })
    }
  },

  // 上传位置到服务器
  uploadLocation(res) {
    uploadLocation({
      latitude: res.latitude,
      longitude: res.longitude,
      accuracy: res.accuracy
    }).catch(err => console.error('上传失败:', err))
  },

  // 获取附近用户（适配新版接口）
  fetchNearbyUsers(currentLocation) {
    getNearbyLocations(currentLocation.latitude, currentLocation.longitude)
      .then(res => {
          console.log(res)
        if (res.data.code === 1 && res.data.data) { // 根据Result结构判断
          this.updateOtherMarkers(res.data.data)
          console.log(this.data.markers)
        } else {
          console.error('获取附近用户失败:', res.data.msg)
        }
      })
      .catch(err => {
        console.error('API请求异常:', err)
        wx.showToast({ title: '获取附近用户失败', icon: 'none' })
      })
  },

  // 更新其他用户标记
updateOtherMarkers(locations) {
    const otherMarkers = locations.map(item => ({
      id: `user_${item.userId}`,
      latitude: item.latitude,
      longitude: item.longitude,
      iconPath: item.avatarUrl || '/images/other-location.png', // 直接使用头像作为标记图标
      width: 40,  // 增大尺寸
      height: 40,
      anchor: { x: 0.5, y: 0.5 },
      callout: {
        content: `${item.userName || '用户'} · ${item.distance.toFixed(0)}米`,
        color: '#000',
        fontSize: 14,
        bgColor: '#ffffff',
        padding: 8,
        borderRadius: 12,
        display: 'ALWAYS', // 始终显示
        textAlign: 'center'
      },
      label: {
        //content: item.userName || '用户',
        color: '#07c160',
        fontSize: 14,
        anchorX: 0,
        anchorY: -20,
        borderWidth: 1,
        borderColor: '#ffffff',
        borderRadius: 4,
        bgColor: '#ffffff',
        padding: 4
      }
    }))
  
    this.setData({
      markers: [
        ...this.data.markers.filter(m => m.id === 'myLocation'), // 保留自己的位置
        ...otherMarkers
      ]
    })
  },

  // 回到我的位置
  centerLocation() {
    this.data.mapContext.moveToLocation()
    this.getLocationAndUpload()
  },

  // 停止共享
  stopSharing() {
    clearInterval(this.data.locationInterval)
    wx.navigateBack()
  },

  onUnload() {
    clearInterval(this.data.locationInterval)
  }
})